﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.IO;

namespace BfLib.Sys
{
    public class BFProcess
    {
        public event DataReceivedEventHandler OutputReceived;

        private StringBuilder _outputSb;
        //private int numOutputLines = 0;

        private string _filename;
        public string ProcessFileName
        {
            get
            {
                return _filename;
            }
        }

        private string _args;
        public string ProcessArguments
        {
            get
            {
                return _args;
            }
        }

        public void RunProcess(bool CaptureOutput, bool WaitForExist, bool HideProcWindow)
        {
            ProcessStartInfo startInfo = new ProcessStartInfo();
            startInfo.CreateNoWindow = HideProcWindow;
            if (CaptureOutput)
            {
                startInfo.RedirectStandardOutput = CaptureOutput;
                startInfo.RedirectStandardError = CaptureOutput;
                startInfo.RedirectStandardInput = CaptureOutput;
            }
            startInfo.UseShellExecute = false;
            startInfo.Arguments = _args;
            startInfo.FileName = _filename;

            Process p = new Process();
            p.StartInfo = startInfo;

            if (CaptureOutput) {p.OutputDataReceived += new DataReceivedEventHandler(OutputHandler);}
            
            p.Start();

            if (CaptureOutput) { p.BeginOutputReadLine(); }
            if ((CaptureOutput) || (WaitForExist)){ p.WaitForExit(); }
            if (CaptureOutput) { p.Close(); }
        }

        public BFProcess(string Filename, string Arguments)
        {
            _outputSb = new StringBuilder();
            _filename = Filename;
            _args = Arguments;
        }

        private void OutputHandler(object sendingProcess, DataReceivedEventArgs outLine)
        {
            // Collect the sort command output.
            if (outLine.Data!=null)
            {
                //_outputSb.Append(String.Format("{0}{1}", outLine.Data, Environment.NewLine));
                //numOutputLines++;
                var evt = this.OutputReceived;
                if (evt != null)
                {
                    evt(this, outLine);
                }

                // Add the text to the collected output.
                //sortOutput.Append(Environment.NewLine + "[" + numOutputLines.ToString() + "] - " + outLine.Data);
            }

            //_outputSb
        }


    }
}
